package com.gaussian.property.admin.module.system.controller.common;

import com.gaussian.property.admin.module.system.vo.system.FileVo;
import com.gaussian.property.module.biz.vo.oss.OssConfig;
import com.gaussian.property.module.quartz.task.BizTask;
import com.songqi.common.core.config.ProjectConfig;
import com.songqi.common.core.constant.Constants;
import com.songqi.common.core.domain.R;
import com.songqi.common.core.exception.CustomException;
import com.songqi.common.core.utils.ServletUtils;
import com.songqi.common.core.utils.StringUtils;
import com.songqi.common.core.utils.file.FileUploadUtils;
import com.songqi.common.core.utils.file.FileUtils;
import com.songqi.common.web.request.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.tika.Tika;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.Paths;
import java.security.NoSuchAlgorithmException;

/**
 * 通用请求处理
 *
 * @author songqi(13776346982)
 */
@Api(tags = "文件、图片操作")
@RestController
@RequestMapping("common/")
public class CommonController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);


    @Resource
    private BizTask bizTask;

    /*@Resource
    private OssClient ossClient;

    @ApiOperation("S3协议文件上传")
    @PostMapping(value = "s3/upload")
    public R<String> uploadObject(@RequestPart MultipartFile file,
                                  @RequestParam String dir,
                                  @ApiParam String bucket) {
        String result = "";
        try {
            result = ossClient.upload(bucket, dir, file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.success(result);
    }*/

    @ApiOperation("(前端传OssToken)根据文件在oss服务器上的存储路径返回访问url")
    @PostMapping("genOssFileUrl")
    public R<String> ossFileUrl(@RequestBody OssConfig ossConfig){
        String url = OssConfig.getOssFileUrl(ossConfig.getObjectFileName(), ossConfig);
        if (url != null){
            return R.success(url);
        }
        return R.error("生成文件url失败");
    }

    @ApiOperation("PC管理端获取oss配置信息")
    @GetMapping("getOssConfig")
    public R<OssConfig> getOssConfig() throws NoSuchAlgorithmException {
        return R.success(bizTask.getOssConfig());
    }

    /**
     * 文件下载请求
     *
     * @param fileName 文件名称
     * @param delete   是否删除
     */
    @GetMapping("download")
    @ApiOperation("文件下载请求")
    public void fileDownload(@ApiParam("文件名称") String fileName,
                             @ApiParam("下载成功后是否删除源文件") Boolean delete, HttpServletResponse response, HttpServletRequest request) {
        try {
            if (!FileUtils.checkAllowDownload(fileName)) {
                throw new CustomException("不允许下载的文件类型");
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = ProjectConfig.getDownloadPath() + fileName;
            Tika tika = new Tika();
            String mimeType = tika.detect(Paths.get(filePath));
            response.setContentType(mimeType);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete) {
                FileUtils.deleteFile(filePath);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 文件上传请求
     */
    @PostMapping("upload")
    @ApiOperation("文件上传")
    public R<FileVo> uploadFile(MultipartFile file) throws Exception {
        try {
            // 上传文件路径
            String filePath = ProjectConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = getUrl() + fileName;
            FileVo fileVo = new FileVo();
            fileVo.setFileName(fileName);
            fileVo.setUrl(url);
            return R.success(fileVo);

        } catch (Exception e) {
            return error();
        }
    }

    /**
     * 本地资源通用下载
     */
    @GetMapping("download/resource")
    @ApiOperation("本地资源通用下载")
    public void resourceDownload(String resource, HttpServletResponse response) {
        try {
            if (!FileUtils.checkAllowDownload(resource)) {
                throw new CustomException("不允许下载的文件类型");
            }
            // 本地资源路径
            String localPath = ProjectConfig.getProfile() ;
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 上传图片
     *
     * @param file
     * @return
     * @throws IOException
     */
    @ApiOperation("上传图片。返回文件访问url")
    @PostMapping("uploadImage")
    public R<String> uploadImage(@RequestPart("file") MultipartFile file) throws IOException {
        if (!file.isEmpty()) {
            String filePath = FileUploadUtils.upload(ProjectConfig.getProfile() + "/image", file);
            return R.success(filePath);
        }
        return R.error("文件上传失败");
    }


    private String getUrl() {
        HttpServletRequest request = ServletUtils.getRequest();
        return getDomain(request);
    }

    private String getDomain(HttpServletRequest request) {
        StringBuffer url = request.getRequestURL();
        String contextPath = request.getServletContext().getContextPath();
        return url.delete(url.length() - request.getRequestURI().length(), url.length()).append(contextPath).toString();
    }

}
